package newpackage;

// Handles a connection of a client to an HelloServer.
// Encapsulates the task of talking with the client in 
// the 'hello' protocol

// Lab session: here are the things you should do
// 1. write a cleanUp method that close streams and sockets no matter what! put calls to this method in the rigt place
// 2. turn the connection handler into an infinite loop that always sends an answer to incoming client string
// 3. take care of removing "this" from the list of clients in the server when it terminates (normally or not)
// (you need to pass the Server reference somehow)

import java.net.*;
import java.io.*;

public class ConnectionHandler implements Runnable {

    // The connection with the client
    private Socket connection;
    private ChatAdministration cAdmin;
    private String userName;
    
    /**
     * Constructs a new ConnectionHandler.
     */
    public ConnectionHandler(Socket connection, ChatAdministration cAdmin, String userName) 
    {
        this.connection = connection;
        this.cAdmin = cAdmin;
        this.userName = userName;
    }
    
    public Socket getSocket()
    {
        return this.connection;
    }
    
    public String getUsername(){
        return this.userName;
    }
       
    public void run() 
    {
        try 
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    
            while(true)
            {
                String message = null;
                try{
                     message = reader.readLine();
                }
                catch(IOException ex){
                }
                if(message == null){
                    cAdmin.notifyDiscconection(this);
                    break;
                }
                cAdmin.sendMessage(message, userName);
            }
        }
        catch (IOException ioe) {} 
    }
}

